package com.elitel.common.businessJdbc;

import java.sql.PreparedStatement;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.elitel.common.utils.XCommonUtils;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class BusinessGeneralPreparedStatementStrategy implements BusinessPreparedStatementStrategy{
    // general format
    public static final SimpleDateFormat ChineseDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:ss:mm");
    public static final boolean MATCH_SUCCESS = true;
    public static final boolean MATCH_FAIL = false;

    public boolean matchPreparedStatementSetMethodByFieldType(PreparedStatement ps, int parameterIndex, Object columnValue, String fieldType) throws Exception{
        String strColumnValue = columnValue.toString();
        if(isContainLeastOneString(fieldType, "int")){
            ps.setInt(parameterIndex, Integer.parseInt(strColumnValue));

        }else if(isContainLeastOneString(fieldType, "long")){
            ps.setLong(parameterIndex, Long.parseLong(strColumnValue));

        }else if(isContainLeastOneString(fieldType, "char", "varchar")){
            ps.setString(parameterIndex, strColumnValue);

        }else if(isContainLeastOneString(fieldType, "datetime", "timestamp")){
            // here check position number if equals 10 position add
            // here maybe exists string type
            Date date = (Date)XCommonUtils.autoHandleDateTimeType(columnValue);

            // if(fieldType instanceof String){
            //     if(strColumnValue.length() == 10){
            //         // "yyyy-MM-dd" will fail
            //         strColumnValue += " 00:00:00";
            //     }
            //     date = ChineseDateFormat.parse(strColumnValue);

            // }else {
            //     date = (Date)columnValue;
            // }

            ps.setTimestamp(parameterIndex,  new java.sql.Timestamp(date.getTime()));

        }else if(isContainLeastOneString(fieldType, "date")){
//            Date date = ChineseDateFormat.parse(strColumnValue);
            Date date = XCommonUtils.autoHandleDateTimeType(columnValue);
            // new date , format the columnValue
            ps.setDate(parameterIndex, new java.sql.Date(date.getTime()));

        }else if(isContainLeastOneString(fieldType, "numeric", "decimal","number", "float", "double")){
            ps.setDouble(parameterIndex, Double.parseDouble(strColumnValue));

        }else{
            // don't handle in this , retain subclass handle
            return MATCH_FAIL;
        }
        return MATCH_SUCCESS;
    }

    public boolean isContainLeastOneString(String content, String... types){
        return XCommonUtils.isContainLeastOneString(content, types);
    }
}
